package com.jzqf.androidserver;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

public class ServerManager {
    private final String TAG = ServerManager.class.getSimpleName();
    private Server mServer;


    /**
     * Create server.
     */
    public ServerManager(final Context context) {
        InetAddress inetAddress = null;
        try {
            /*
             * 10.1.21.125
             * 10.144.51.205
             */
            inetAddress = InetAddress.getByName("192.168.0.105");
//            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            Log.i(TAG, "ip error " + e.getMessage());
        }

        final InetAddress finalInetAddress = inetAddress;
        mServer = AndServer.webServer(context)
                .inetAddress(inetAddress)
                .port(8027)
                .timeout(10, TimeUnit.SECONDS)
                .listener(new Server.ServerListener() {
                    @Override
                    public void onStarted() {
                        Log.i(TAG, "onStarted="+ finalInetAddress.getHostAddress());
                        Toast.makeText(context, "开启成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onStopped() {
                        Log.i(TAG, "onStopped");
                        Toast.makeText(context, "停止", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onException(Exception e) {
                        e.printStackTrace();
                        Toast.makeText(context, "异常" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "onException" + e.getMessage());
                    }
                })
                .build();
    }

    /**
     * Start server.
     */
    public void startServer() {
        if (mServer.isRunning()) {
            // TODO The server is already up.
        } else {
            mServer.startup();
        }
    }

    /**
     * Stop server.
     */
    public void stopServer() {
        if (mServer.isRunning()) {
            mServer.shutdown();
        } else {
            Log.w("AndServer", "The server has not started yet.");
        }
    }

}
